﻿using System.Linq;
using System.Linq.Expressions;
using RatingAuthor;

namespace ConditionTreeTestStand.Nodes
{
  public class GroupNodeViewModel : NodeViewModel
  {
    #region ' Public Properties '

    public override bool CanAddGroupChild { get { return true; } }
    public override bool CanAddConditionChild { get { return true; } }
    public override bool CanSwitchNodeType
    {
      get { return !Children.Any(c => c is ConditionNodeViewModel); }
    }

    #endregion

    /// <summary>Design time constructor</summary>
    public GroupNodeViewModel() 
      : base(null, null)
    {
    }

    public GroupNodeViewModel(NodeViewModel parent, NodeContext nodeContext)
      : base(parent, nodeContext)
    {
    }

    #region ' Changes Notification '

    protected override void OnChildrenChanged()
    {
      base.OnChildrenChanged();
      NotifyOfPropertyChange(() => CanSwitchNodeType);
    }

    #endregion

    #region ' Implementation '

    public override bool TestBook(Book b)
    {
      var res = Children.Select(c => c.TestBook(b));
      return (bool)Operator.Apply(res.Cast<object>());
    }

    protected override NodeViewModel CreateReplacementNode()
    {
      return new ConditionNodeViewModel(null, NodeContext);
    }

    public override string ToString()
    {
      return "(" + string.Join(" " + Operator.Symbol + " ", Children) + ")";
    }

    public override Expression GetExpression()
    {
      return Operator.GetExpression(
        Children.Select(c => c.GetExpression()).
        Where(exp => exp != null));
    }

    #endregion
  }
}